import Axios from 'axios'
import { App } from '@vue/runtime-dom'

import { ElMessage } from 'element-plus'

export const prefixDefault = '/prodapi'

export const parseURLAction = function (action: string, prefix = prefixDefault) {
  return `${prefix}${prefix.endsWith('/') ? '' : '/'}${action}`
}

const parseResult = async function (result: { code: number; message: any; data: any }) {
  if (result.code === 200) {
    if (result.message) {
      // await ElMessage.success(result.message)
    }
    return result.data
  } else {
    ElMessage.error(result.message || '请求失败，请稍后重试')
    throw result.message || '请求不成功'
  }
}

/**
* @name: 封装axios get方法
* @desc: 描述
* @author: Ceart
* @email: 1871321876@qq.com
* @date: 2021-12-21
* @param action 请求连接
* @param params 请求参数
* @param configRaw 回调方法
*/
export const $get = async function (action: string, params: any = {}, configRaw: any = {}) {
  const token = localStorage.getItem('token')
  if (token) {
    configRaw.Authorization = `Bearer ${token}`
  }

  const urlAction = parseURLAction(action, configRaw?.prefix)

  const config = Object.assign({ params }, configRaw)

  const response = await Axios.get(urlAction, config)
  return parseResult(response.data)
}

export const $post = async function (action: string, params: any = {}, configRaw: any = {}, alertUnSuccess = false) {
  const token = localStorage.getItem('token')
  if (token) {
    configRaw.Authorization = `Bearer ${token}`
  }

  const urlAction = parseURLAction(action, configRaw?.prefix)

  const config = Object.assign({}, configRaw)

  if (params instanceof FormData) {
    if (typeof config.headers === 'object' && config.headers) {
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      config.headers = { 'Content-Type': 'multipart/form-data' }
    }
  }

  const response = await Axios.post(urlAction, params, config)

  return parseResult(response.data)
}

export const $jump = async function (action: string, params: any = {}, configRaw: any = {}) {
  const urlAction = parseURLAction(action, configRaw?.prefix)
  let query = ''

  for (const key in params) {
    if (params[key]) {
      if (typeof params[key] === 'object') {
        query += `&${key}=${JSON.stringify(params[key])}`
      } else {
        query += `&${key}=${params[key]}`
      }
    }
  }
  query = query.replace(/^&/, '')

  window.location.href = `${urlAction}?${query}`
}

export const install = function (app: App) {
  app.provide('$get', $get)
  app.provide('$post', $post)
  app.provide('$jump', $jump)
}
